import React, { FC, useState, useEffect } from 'react'
import { Input } from 'antd'
import { useNavigate, useLocation, useSearchParams } from 'react-router-dom'
import type { ChangeEvent } from 'react'
import { SEARCH_LIST_KEYWORD } from '../../constant'
const { Search } = Input;
// 要将其改为受控组件
const ListSearch: FC = () => {
    const [value, setValue] = useState('')
    const nav = useNavigate()
    const { pathname } = useLocation()
    const [searchParams] = useSearchParams()
    // 点击搜索时 要将搜索的内容作为参数传递给url并进行跳转
    const onSearchHandle = (value: string) => {
        nav({
            pathname,
            search: `${SEARCH_LIST_KEYWORD}=${value}`
        })
    }
    // 监听url参数的变化
    useEffect(() => {
        const curVal = searchParams.get(SEARCH_LIST_KEYWORD) || ""
        setValue(curVal)
    }, [searchParams])
    const inpChangeHandle = (event: ChangeEvent<HTMLInputElement>) => {
        setValue(event.target.value)
    }
    return <Search
        placeholder='请输入搜索内容'
        onSearch={onSearchHandle}
        value={value}
        allowClear
        onChange={inpChangeHandle}
        style={{ width: 200 }}
    />
}

export default ListSearch